package com.example.bluetoothclicker.func

import android.app.Service
import android.bluetooth.BluetoothSocket
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log

class BluetoothService : Service() {

    private val binder = BluetoothBinder()
    private val maxConnections = 5 // 最大连接数

    override fun onCreate() {
        super.onCreate()
        // 初始化服务端
        BluetoothConnectionManager.initializeServer(
            maxConnections = maxConnections,
            onClientConnected = { socket -> handleClientConnection(socket) },
            onStatusChanged = { status -> Log.d("BluetoothService", status) }
        )
    }

    // 启动服务端
    fun startServer() {
        BluetoothConnectionManager.startServer(
            onClientConnected = { socket -> handleClientConnection(socket) },
            onStatusChanged = { status -> Log.d("BluetoothService", status) }
        )
    }

    // 处理客户端连接逻辑
    private fun handleClientConnection(socket: BluetoothSocket) {
        Log.d("BluetoothService", "客户端已连接: ${socket.remoteDevice.name}")
        // 在此处处理客户端连接的具体逻辑
    }

    override fun onBind(intent: Intent?): IBinder {
        return binder
    }

    override fun onDestroy() {
        super.onDestroy()
        BluetoothConnectionManager.stopServer()
    }

    // Binder类，用于绑定服务
    inner class BluetoothBinder : Binder() {
        fun getService(): BluetoothService = this@BluetoothService
    }
}
